//
//  MYGFireVoiceViewController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/25.
//

import UIKit
import AVFoundation

class MYGFireVoiceViewController: MYGBaseController {
    // MARK: - Property
    let model: MYGChatVoiceCellModel
    var seeAction: (()->Void)?
    init(model: MYGChatVoiceCellModel) {
        self.model = model
        
        super.init(nibName: nil, bundle: nil)
        
        modalPresentationStyle = .overFullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var player: AVAudioPlayer?
    let session:AVAudioSession = AVAudioSession.sharedInstance()
    var playerTimer: Timer?
    
    // MARK: -
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
        
        contentLabel.text = "\(model.duration)"
        imageView.startAnimating()
        if let url = model.localPath {
            self.playRecord(url, isNetwork: false)
        } else {
            self.playRecord(model.webPath, isNetwork: true)
        }
        
        
        
    }
    // MARK: - UI
    private func configUI() {
        view.backgroundColor = .rgba(0, 0, 0, 0.69)
        view.addSubview(mainView)
        mainView.addSubview(imageView)
        mainView.addSubview(contentLabel)
        
        mainView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(113)
            make.height.equalTo(38)
        }
        
        imageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(13)
            make.centerY.equalToSuperview()
            make.width.equalTo(12)
            make.height.equalTo(20)
        }
        
        contentLabel.snp.makeConstraints { make in
            make.left.equalTo(imageView.snp.right).offset(10)
            make.centerY.equalToSuperview()
        }
        
    }
    
    // MARK: - lazy load
    private lazy var mainView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(247, 247, 247, 1)
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 4
        return view
    }()
    
    private lazy var imageView: UIImageView = {
//        let imgV = LottieAnimationView(name: "Lottie/voice")
        let imgs: [UIImage] = [UIImage(named: "Chat/voice3")!, UIImage(named: "Chat/voice1")!,UIImage(named: "Chat/voice2")!]
        let imgV = UIImageView(image: UIImage(named: "Chat/voice3"))
        imgV.contentMode = .left
        imgV.animationImages = imgs
        imgV.animationDuration = 1
        imgV.animationRepeatCount = 0
//        imgV.startAnimating()
        return imgV
    }()
    
    private lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(12)
        label.textColor = .rgba(51, 51, 51, 1)
        return label
    }()
    
    private func playRecord(_ url: String, isNetwork: Bool) {
        if session.category != AVAudioSession.Category.playback {
            do {
                try session.setCategory(AVAudioSession.Category.playback)
            } catch {
                print("播放模式切换失败：\(error.localizedDescription)")
            }
        }
        
        if isNetwork {
            do {
                guard let data = try? Data(contentsOf: URL(string: url)!) else {
                    return
                }
                
                player = try AVAudioPlayer(data: data)
                player?.delegate = self
                player?.prepareToPlay()
                player?.play()
                
                let timer = Timer.init(timeInterval: 1, repeats: true) {[weak self] timer in
                    guard let self = self else {
                        return
                    }
                    if let time = self.player?.currentTime {
//                        self.playCell?.timeChange(false, time: Int(time))
                        self.contentLabel.text = "\(model.duration - Int(time))"
                    }
                    
                }
                
                RunLoop.current.add(timer, forMode: .common)
                self.playerTimer = timer
            } catch {
                print("播放失败:\(error.localizedDescription)")
            }
            return
        }
        
        do {
            let file_path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending(url ?? "")

            player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: file_path!))
            player?.delegate = self
            player?.prepareToPlay()
            player?.play()
            
            let timer = Timer.init(timeInterval: 1, repeats: true) {[weak self] timer in
                guard let self = self else {
                    return
                }
                if let time = self.player?.currentTime {
                    self.contentLabel.text = "\(model.duration - Int(time))"
                }
                
            }
            
            RunLoop.current.add(timer, forMode: .common)
            self.playerTimer = timer
        } catch {
            print("播放失败:\(error.localizedDescription)")
        }
    }
    
    private func stopPlay() {
        self.player?.stop()
        self.playerTimer?.invalidate()
        self.player = nil
        self.playerTimer = nil

        self.contentLabel.text = "\(model.duration)"

        self.seeAction?()
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.stopPlay()
        self.seeAction?()
        self.dismiss(animated: false)
    }
}

extension MYGFireVoiceViewController: AVAudioPlayerDelegate {
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        self.playerTimer?.invalidate()
        self.playerTimer = nil
        self.player = nil
        self.contentLabel.text = "\(model.duration)"
        self.imageView.stopAnimating()
        
        self.seeAction?()
        self.dismiss(animated: false)
    }
}
